/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.mqtt.broker.factory

import cool.taomu.mqtt.broker.entity.MessageEntity
import cool.taomu.mqtt.broker.utils.MqttUtils
import cool.taomu.mqtt.broker.utils.impl.DataStorage
import cool.taomu.utils.inter.IStorage
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.mqtt.MqttFixedHeader
import io.netty.handler.codec.mqtt.MqttMessage
import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader
import io.netty.handler.codec.mqtt.MqttMessageType
import io.netty.handler.codec.mqtt.MqttQoS
import java.util.HashSet
import org.slf4j.LoggerFactory

class PubRelRequest implements IProcess {
	val LOG = LoggerFactory.getLogger(PubRelRequest);

	IStorage cache = new DataStorage();

	override request(ChannelHandlerContext ctx, MqttMessage mqttMessage) {
		var clientId = MqttUtils.getClientId(ctx.channel);
		LOG.info("执行了MQTT PubRel 命令 : " + clientId);
		// TODO 需要添加判断clientId
		var idVariableHeader = mqttMessage.variableHeader as MqttMessageIdVariableHeader;
		var msgId = idVariableHeader.messageId();
		// 回给订阅者这个一个REL命令
		var qos2 = cache.get("mqtt-qos2-message",#[clientId, msgId].join("#")) as HashSet<?>;
		for (q : qos2) {
			var msg = q as MessageEntity;
			var header = new MqttFixedHeader(MqttMessageType.PUBREL, false, MqttQoS.AT_MOST_ONCE, false, 0);
			var varHeader = MqttMessageIdVariableHeader.from(msgId);
			msg.senderChannel.writeAndFlush(new MqttMessage(header, varHeader));
			cache.remove("mqtt-qos2-message",#[clientId, msgId].join("#"));
			msg.senderChannel = ctx.channel;
			var senderId = msg.senderId;
			msg.senderId = clientId;
			cache.put("mqtt-qos2-message",#[senderId,msgId].join("#"), msg);
		}
	}
}
